/**
 * @file lsm303d_platform.c
 * @author your name (you@domain.com)
 * @brief 为lsm303d驱动模块能够适配不同的设备，特提供此文件以满足不同的底层实现
 * @version 0.1
 * @date 2022-12-20
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include "lsm303d_spi.h"
#include "system_support.h"


#ifndef LSM303D_SPI_HANDLE
#error	"Please define LSM303D_SPI_HANDLE forward!"
#endif

#define LSM303D_I2C_TIME_OUT    10
#define LSM303D_SPI_MAX_LEN     32
#define LSM303D_SPI_MAX_WAIT   10

uint8_t lsm303d_rx_buff[LSM303D_SPI_MAX_LEN];
uint8_t lsm303d_tx_buff[LSM303D_SPI_MAX_LEN];

int lsm303d_read_reg(uint8_t reg,	uint8_t * buf, uint32_t len){
	int8_t ret = 0;
	uint8_t read_len = len + 1;
	
	memset(lsm303d_tx_buff, 0, read_len);
	lsm303d_tx_buff[0] = reg | 0xC0; 

	if(buf == NULL){
		elog_error("lsm303d_spi", "param error");
		return -1;
	}

	if(read_len >= LSM303D_SPI_MAX_LEN){
		elog_error("lsm303d", "param error");
		return -1;
	}
	
	HAL_GPIO_WritePin(LSM303D_NSS_GPIO, LSM303D_NSS_PIN, GPIO_PIN_RESET);
	
	HAL_SPI_TransmitReceive(LSM303D_SPI_HANDLE, lsm303d_tx_buff, lsm303d_rx_buff, read_len, LSM303D_SPI_MAX_WAIT);
	
	HAL_GPIO_WritePin(LSM303D_NSS_GPIO, LSM303D_NSS_PIN, GPIO_PIN_SET);

	memcpy(buf, &lsm303d_rx_buff[1], len);

	return ret;
}

int lsm303d_write_reg(uint8_t reg,  uint8_t * buf, uint32_t len)
{
	int8_t ret = 0;
	uint8_t write_len = len + 1;

	if(buf == NULL){
		elog_error("lsm303d_spi", "param error");
		return -1;
	}

	if(write_len >= LSM303D_SPI_MAX_LEN){
		elog_error("lsm303d_spi", "param error");
		return -1;
	}
	
	lsm303d_tx_buff[0] = reg ;//& 0x7f
	
	memcpy(lsm303d_tx_buff + 1, buf, len);
	
	HAL_GPIO_WritePin(LSM303D_NSS_GPIO, LSM303D_NSS_PIN, GPIO_PIN_RESET);

	ret += HAL_SPI_Transmit(LSM303D_SPI_HANDLE, lsm303d_tx_buff, write_len, LSM303D_SPI_MAX_WAIT);
	
	HAL_GPIO_WritePin(LSM303D_NSS_GPIO, LSM303D_NSS_PIN, GPIO_PIN_SET);

	return ret;
}
